using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI;
using System.Windows.Controls;
using System.Globalization;

namespace SPGael.CustomFields
{
    public class CustomRegularExpressionValidatorField : Microsoft.SharePoint.SPFieldText
    {
        public CustomRegularExpressionValidatorField(SPFieldCollection fields, string fieldName)
            : base(fields, fieldName)
        {
        }

        public CustomRegularExpressionValidatorField(SPFieldCollection fields, string typeName, string displayName)
            : base(fields, typeName, displayName)
        {
        }

        public override string GetValidatedString(object value)
        {
            // Check value
            if ((this.Required == true)
                && ((value == null)
                || ((String)value == "")))
            {
                throw new SPFieldValidationException(this.Title + " cannot be empty.");
            }
            
            // Check default arguments
            if (string.IsNullOrEmpty(Convert.ToString(this.GetCustomProperty("myRegEx"))))
            {
                throw new SPFieldValidationException(this.Title + " has not regular expression filled out (set in the design mode)");
            }
            if (string.IsNullOrEmpty(Convert.ToString(this.GetCustomProperty("myErrorMessage"))))
            {
                throw new SPFieldValidationException(this.Title + " has not error message filled out (set in the design mode)");
            }

            // Fire the validation rule if field is not null
            if (value != null && (String)value != "")
            {
                CustomRegularExpressionValidatorValidationRule rule = new CustomRegularExpressionValidatorValidationRule();
                Triplet myField = new Triplet(this.GetCustomProperty("myRegEx"), value, this.GetCustomProperty("myErrorMessage"));
                ValidationResult result = rule.Validate(myField, CultureInfo.InvariantCulture);

                // Error on validation
                if (!result.IsValid)
                {
                    throw new SPFieldValidationException((String)result.ErrorContent);
                }
            }
            return base.GetValidatedString(value);
        }


        public override BaseFieldControl FieldRenderingControl
        {
            get
            {
                BaseFieldControl control = new CustomRegularExpressionValidatorFieldControl();
                control.FieldName = this.InternalName;
                return control;
            }
        }
    }
}
